import React, { useState, useEffect } from 'react';
import routes from '../../router';
import { Layout, Menu } from 'antd';
import router from 'umi/router';

const { Sider, Content } = Layout;
const { SubMenu } = Menu;
const routeFilter = {};
routes.forEach(item => {
  item.routes.forEach(v => {
    if (v.isInMenu) {
      routeFilter[v.path] = v;
    }
  });
});

function BasicLayout (props) {
  const [selectedMenu, setSelectedMenu] = useState(''); // 选中的菜单 key
  const [selectedSubMenu, setSelectedSubMenu] = useState(''); // 展开/关闭的子菜单 key

  useEffect(() => {
    setSelectedMenu(props.location.pathname);
    const subMenuKey = '/' + props.location.pathname.split('/')[1];
    if (routeFilter[subMenuKey] && routeFilter[subMenuKey].routes) {
      setSelectedSubMenu(subMenuKey);
    }
  }, [props.location.pathname]);

  /**
   * 渲染菜单
   * @param item
   * @param index
   * @returns {*}
   */
  function renderSubMenu (item, index) {
    if (item.routes) {
      return (
        <SubMenu key={ item.path } title={ item.menuName } onTitleClick={ onSubMenuClick }>
          { item.routes ? item.routes.map(v => {
            return (
              <Menu.Item key={ v.path }>
                { v.menuName }
              </Menu.Item>
            );
          }) : null }
        </SubMenu>
      );
    } else {
      return (
        <Menu.Item key={ item.path }>
          { item.menuName }
        </Menu.Item>
      );
    }
  }

  /**
   * 子菜单展开、关闭操作
   * @param e
   */
  function onSubMenuClick (e) {
    const { key } = e;
    if (selectedSubMenu === key) {
      setSelectedSubMenu('');
    } else {
      setSelectedSubMenu(key);
    }
  }

  function onMenuItemClick (e) {
    setSelectedMenu(e.key);
    router.push(e.key);
  }

  return (
    <Layout>
      <Sider width={ 200 } className={ { background: '#fff' } }>
        <Menu
          mode="inline"
          selectedKeys={ [selectedMenu] }
          openKeys={ [selectedSubMenu] }
          onClick={ onMenuItemClick }
          style={ { height: '100%', borderRight: 0 } }
        >
          { Object.keys(routeFilter).map((key, index) => renderSubMenu(routeFilter[key], index)) }
        </Menu>
      </Sider>
      <Content>
        { props.children }
      </Content>
    </Layout>
  );
}

export default BasicLayout;
